package web;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import entites.UniteEnseignement;

import auth.service.Auth;
import auth.service.User;
public class AuthController extends SimpleFormController {

	private User user;
	private Auth auth;


	public AuthController() {
		setCommandClass(User.class);
	}
	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		User user =new User();
		user.setAuth(0);
		return user;
	}
/*
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		logger.info("formulaire de login");
		return new ModelAndView("loginForm");
	}*/


	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		User user = (User)binder.getTarget();
		String login = null ;
		String motDePasse = null;
		try {
			login = request.getParameter("login");
			motDePasse = request.getParameter("motDePasse");
			
		} catch (Exception e) {}		
		if ((login!= null) || (motDePasse!=null)) {
			user.setLogin(login);
			user.setMotDePasse(motDePasse);
			request.getSession().setAttribute("connecte", "connecte");

		}    
	}
	

	@Override
	public ModelAndView onSubmit (HttpServletRequest request,
			HttpServletResponse response,Object Command,BindException errors) throws ServletException {

		User u=(User)Command;
		user=auth.login(u);
		if(user.getAuth()==1 || user.getAuth()==2){
			System.out.println("==============================coucou je suis connecte =======================");

			request.getSession().setAttribute("user", user);
			return new ModelAndView(new RedirectView("accueil.htm"));
		}
		else
			return new  ModelAndView(new RedirectView("loginForm.htm"));

	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Auth getAuth() {
		return auth;
	}

	public void setAuth(Auth auth) {
		this.auth = auth;
	}


}
